#ifndef grocerylistview_h
#define grocerylistview_h

#include "juce_amalgamated.h"
#include "GroceryListViewList.h"
#include "GroceryAddButton.h"
#include "../../MiscGraphics.h"

class GrogeryListPanel;

class GroceryListViewport: public Viewport {
private:
	GroceryListViewList* listView;

public:
	GroceryListViewport(GroceryListViewList* lv) :
		listView(lv) {

	}

	void visibleAreaChanged(int x, int y, int w, int h) {
		listView->setCurrentYOffset(y);
	}
};

class GroceryListView: public Component {
private:
	GroceryListViewList* listView;
	GroceryListViewport* lvPort;
	GroceryAddButton* addButton;

	map<String, vector<Eatable> > groceryItems;

	const static int spacer = 7;
	NutritionalInfo info;

public:
	GroceryListView() {
		listView = new GroceryListViewList(this, groceryItems);
		addAndMakeVisible(lvPort = new GroceryListViewport(listView));
		lvPort->setViewedComponent(listView);

		addAndMakeVisible(addButton = new GroceryAddButton());
	}

	~GroceryListView() {
		delete lvPort;
		delete addButton;
	}

	void paint(Graphics& g) {
		calculateNutrients();
		Rectangle r(spacer, 0, 3 * getWidth() / 7, getHeight());

		MiscGraphics::drawNutritionalDiagram(info, g, r);

		//		Rectangle r2(4 * getWidth() / 7, getHeight() - 70, 3 * getWidth() / 7, 70);
		//		g.setColour(Colours::black);
		//		g.drawRect(r2);
	}

	void calculateNutrients() {
		NutritionalInfo allNutrients;
		for (map<String, vector<Eatable> >::iterator mit = groceryItems.begin(); mit
				!= groceryItems.end(); ++mit) {
			if (mit->second.size()) {
				for (vector<Eatable>::iterator vit = mit->second.begin(); vit != mit->second.end(); ++vit) {
					allNutrients += vit->getNutritionalInfo();
				}
			}
		}
		info = allNutrients;
	}

	void resized() {
		lvPort->setBounds(3 * getWidth() / 7 + 6, 55, 4 * getWidth() / 7, getHeight() - 55);
		listView->setBounds(0, 0, 4 * getWidth() / 7 - 7, getHeight() - 55);
		addButton->setBounds(3 * getWidth() / 7 + 6, 0, 4 * getWidth() / 7 - 7, 50);
	}

	void addItem(Eatable& food) {
		groceryItems[Eatable::groups[food.gid]].push_back(food);
		listView->setBounds(0, 0, 4 * getWidth() / 7 - 7, std::max(listView->getTotalHeight(),
				getHeight() - 55));
		listView->repaint();
		lvPort->repaint();
		repaint();
	}

	void setListPanel(GroceryListPanel* p);

	void clearList() {
		groceryItems.clear();
	}
};

#endif

